define(['moment','jqplot-bar', 'jqplot-pointLabels'], function (moment) {
    return ['$scope', '$rootScope', '$mdDialog', 'MMWService', '$filter', '$stateParams', '$timeout', 'config', '$calculater',
        function ($scope, $rootScope, $mdDialog, $MMWService, $filter, $stateParams, $timeout, config, $calculater) {
            
            $scope.init = function(){
                $scope.loading_time = moment().format('YYYY-MM-DD HH:mm:ss');
                // 折線圖 x軸 取當月最後一天的日期
                $scope.endMonthDate = moment().endOf('month').format("YYYY-MM-DD").split('-');
                // 當月 request
                $scope.month_content = {
                    work_order_condition:[
                        { moduelType: 'work_order', dateType: 'mo' }
                    ]
                };
                // 當週 request
                $scope.week_content = {
                    work_order_condition:[
                        { moduelType: 'work_order', dateType: 'wk' }
                    ]
                };
                init_oneMonth();
            };
            
            $scope.back = function(){
                $rootScope.changeProgram('menu', {}, true);
            };

            // 載入取得所有工廠資料，並預帶第一筆資料
            function init_oneMonth(){
                getAllDateData($scope.month_content, function(data){
                    if(data && data.work_order_data.length > 0){
                        // factoryList 載入取得的所有工廠資料，讓使用者可以開窗更換
                        $scope.factoryList = data.work_order_data;
                        $scope.nowState = 'Month';
                        $scope.factory_no = data.work_order_data[0].factory_no;
                        $scope.factory_name = data.work_order_data[0].factory_name;
                        $scope.allDate = data.work_order_data[0].expected_work_order_date;
                        // 預計產量
                        var except_qty = data.work_order_data[0].expected_work_order_date.map(function(item){
                            return item.e_qty;
                        });
                        // 實際產量
                        var actual_qty = data.work_order_data[0].expected_work_order_date.map(function(item){
                            return item.a_qty;
                        });
                        // 總預計產量
                        $scope.except_qty = except_qty.reduce(function(accumulator, currentValue){
                            return accumulator + currentValue;
                        });
                        // 總實際產量
                        $scope.actual_qty = actual_qty.reduce(function(accumulator, currentValue){
                            return accumulator + currentValue;
                        });
                        lineGraph(except_qty, actual_qty, $scope.endMonthDate[2], 'Month');
                    } else {
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                    };
                });
            };

            // 開窗更換工廠編號
            $scope.changeFactoryNo = function(){
                $scope.$root.showQueryList({
                    key:'factory_no',
                    header : [
                        {label: $filter('translate')('工廠編號'), code:'factory_no'},
                        {label: $filter('translate')('工廠名稱'), code:'factory_name'}
                    ],
                    query: function(conditions, feedback){
                        feedback($scope.factoryList);
                    },
                    confirm: function(selectItem, dialog){
                        dialog.hide();
                        $scope.factory_no = selectItem.factory_no;
                        $scope.factory_name = selectItem.factory_name;
                        $scope.allDate = selectItem.expected_work_order_date;
                        // 預計產量
                        var except_qty = selectItem.expected_work_order_date.map(function(item){
                            return item.e_qty;
                        });
                        // 實際產量
                        var actual_qty = selectItem.expected_work_order_date.map(function(item){
                            return item.a_qty;
                        });
                        // 總預計產量
                        $scope.except_qty = except_qty.reduce(function(accumulator, currentValue){
                            return accumulator + currentValue;
                        });
                        // 總實際產量
                        $scope.actual_qty = actual_qty.reduce(function(accumulator, currentValue){
                            return accumulator + currentValue;
                        });
                        if($scope.nowState == 'Month'){
                            lineGraph(except_qty, actual_qty, $scope.endMonthDate[2], 'Month');
                        } else if ($scope.nowState == 'Week'){
                            lineGraph(except_qty, actual_qty, 7, 'Week');
                        }
                    }
                });
            };

            // 更新
            $scope.upDate = function(){
                $scope.loading_time = moment().format('YYYY-MM-DD HH:mm:ss');
                if($scope.nowState == 'Month'){
                    getNowFactoryData($scope.month_content, 'Month');
                } else if($scope.nowState == 'Week'){
                    getNowFactoryData($scope.week_content, 'Week');
                }
            };
            
            // 當月
            $scope.getOneMonth = function(){
                getNowFactoryData($scope.month_content, 'Month');
            };

            // 當週
            $scope.getOneWeek = function(){
                getNowFactoryData($scope.week_content, 'Week');
            };

            // 取得當下選擇的工廠資料
            function getNowFactoryData(content, nowState){
                getAllDateData(content, function(data){
                    if(data && data.work_order_data.length > 0){
                        var nowfactoryNoData = data.work_order_data.filter(function(item){
                            return item.factory_no == $scope.factory_no;
                        });
                        $scope.nowState = nowState;
                        $scope.factory_no = nowfactoryNoData[0].factory_no;
                        $scope.factory_name = nowfactoryNoData[0].factory_name;
                        $scope.allDate = nowfactoryNoData[0].expected_work_order_date;
                        // 預計產量
                        var except_qty = nowfactoryNoData[0].expected_work_order_date.map(function(item){
                            return item.e_qty;
                        });
                        // 實際產量
                        var actual_qty = nowfactoryNoData[0].expected_work_order_date.map(function(item){
                            return item.a_qty;
                        });
                        // 總預計產量
                        $scope.except_qty = except_qty.reduce(function(accumulator, currentValue){
                            return accumulator + currentValue;
                        });
                        // 總實際產量
                        $scope.actual_qty = actual_qty.reduce(function(accumulator, currentValue){
                            return accumulator + currentValue;
                        });
                        if(nowState == 'Month'){
                            lineGraph(except_qty, actual_qty, $scope.endMonthDate[2], 'Month');
                        } else if (nowState == 'Week'){
                            lineGraph(except_qty, actual_qty, 7, 'Week');
                        }
                    } else {
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                    };
                });
            };

            // 取得折線圖
            function lineGraph(except_qty, actual_qty, endMonthDate, nowState){
                // 為了避免重疊，每呼叫一次折線圖要先刪除當下的折線圖後，再產生出新的
                $('#lineGraph').empty();
                $('#lineGraph').css('min-width', '100%').css('min-height', '70%');
                if(nowState == 'Week'){
                    $.jqplot('lineGraph', [except_qty,actual_qty], {  
                        grid: { 
                            backgroundColor: '#ffffff', 
                            drawBorder:false,
                            shadow:false
                        }, 
                        seriesColors:["#293F5D","#ffb307"],
                        axes: {
                            // X軸
                            xaxis: {
                                // X軸起始
                                min: 1, 
                                // X軸最終
                                max: endMonthDate,
                                tickOptions: { 
                                    // 不顯示小數點
                                    formatString: "%d" 
                                },
                                // 當周資料較少，所要完整呈現x軸
                                renderer: $.jqplot.CategoryAxisRenderer
                            },
                            // Y軸
                            yaxis: {
                                // Y軸起始
                                pad: 0,
                            }
                        },
                    }); 
                } else {
                    $.jqplot('lineGraph', [except_qty,actual_qty], {  
                        grid: { 
                            backgroundColor: '#ffffff', 
                            drawBorder:false,
                            shadow:false
                        }, 
                        seriesColors:["#293F5D","#ffb307"],
                        axes: {
                            // X軸
                            xaxis: {
                                // X軸起始
                                min: 1, 
                                // X軸最終
                                max: endMonthDate,
                                tickOptions: { 
                                    // 不顯示小數點
                                    formatString: "%d" 
                                }
                            },
                            // Y軸
                            yaxis: {
                                // Y軸起始
                                pad: 0,
                            }
                        },
                    }); 
                };
            };

            // 取得工單資料
            $scope.openOpData = function(item){
                var content = {
                    work_order_condition:[
			            { moduelType: 'work_detail', date: item.date_no, factory_no: $scope.factory_no},
                    ]
                };
                getAllDateData(content, function(data){
                    if(data && data.work_detail.length > 0){
                        if(!item.opData || item.opData.length == 0){
                            item.switch = true;
                            item.opData = data.work_detail || [];
                            for(var i = 0; i < item.opData.length; i++){
                                item.opData[i].pieChart_config = {
                                    innerRadiusRate:0.8,
                                    isShowLabel:false,
                                    radius:37
                                };
                                item.opData[i].loading_op_qty = [{color:'rgb(73, 168, 238)', value:0},{color:'rgb(239, 239, 239)', value:0}];
                                item.opData[i].loading_op_qty[0].value = ((item.opData[i].inv_qty / item.opData[i].mo_qty) * 100).toFixed(2);
                                item.opData[i].loading_op_qty[1].value = 100 - item.opData[i].loading_op_qty[0].value;
                                if(item.opData[i].loading_op_qty[0].value >= 100){
                                    item.opData[i].loading_op_qty[0].color = 'rgb(104, 189, 132)';
                                }
                            }; 
                            item.style = {'display':'block'};
                        } else {
                            item.switch = false;
                            item.opData = [];
                            item.style = {'display':'none'};
                        };
                    } else {
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                    };
                });
            };

            // 取得生產批資料
            $scope.openPlotData = function(item){
                var content = {
                    work_order_condition:[
			            { moduelType: 'product_detail', mo_no: item.mo_no },
                    ]
                };
                getAllDateData(content, function(data){
                    if(data && data.product_detail.length > 0){
                        if(!item.plotData){
                            item.switch = true;
                            item.plotData = data.product_detail || [];
                            item.style = {'display':'block'};
                        } else {
                            item.switch = false;
                            item.plotData = undefined;
                            item.style = {'display':'none'};
                        };
                    } else {
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                    };
                });
            };

            // 生產批資料長條圖比例
            $scope.plotData_barChart = function(item){
                var value = (item.inv_qty / item.input_qty) * 100;
                if(value == 100){
                    return {width: value + '%',background: 'linear-gradient(115deg, rgba(52, 170, 111, 0.8) 28%, rgba(26, 183, 204, 0) 200%)'};
                } else {
                    return {width: value + '%',background: 'linear-gradient(115deg, rgba(92, 137, 184, 0.8) 28%, rgba(26, 183, 204, 0) 200%)'};
                };
            };

            // 取得每月的所有資料
            function getAllDateData(content, callback){
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_WIP.workshop_output_info_get',
                    content : content,
                    success : function(data){
                        if(callback)
                            callback(data);
                    }
                });
            };

        }
    ];
});
